package org.microdream.easy.deploy.service;

import ice.server.comm.BaseOperateResult;
import ice.server.comm.BaseServiceImpl;
import ice.server.comm.CommRepository;
import ice.server.comm.ParamBulider;
import ice.tool.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.microdream.easy.deploy.dao.DProjectRepository;
import org.microdream.easy.deploy.po.DProject;
import org.microdream.easy.deploy.po.DUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title: 项目服务层
 * @author:沈明可
 * @create: 2019-09-15 20:49
 */
@Service
public class DProjectService extends BaseServiceImpl<DProject, Integer> {

    @Resource
    private DProjectRepository dProjectRepository;

    @Resource
    private DAppService dAppService;

    @Override
    public CommRepository<DProject, Integer> getRepository() {
        return dProjectRepository;
    }

    @Override
    public Integer getIdenty(DProject dProject) {
        return dProject.getId();
    }

    /**
     * 功能描述:〈项目新增〉
     * @param dProject 项目实体类
     * @param dUser 当前登录用户
     * @return : ice.server.comm.BaseOperateResult
     * @author : 沈明可
     * @date : 2019/9/15 20:56
     * User :
     */
    public BaseOperateResult add(DProject dProject, DUser dUser){
        dProject.setRentCode(dUser.getRentCode());
        dProject.setCreator(dUser.getUserAccount());
        dProject.setCreateTime(new Timestamp(System.currentTimeMillis()));
        dProject.setCreatorName(dUser.getUserName());
        return BaseOperateResult.add(this.save(dProject));
    }

    /**
     * 功能描述:〈项目修改〉
     * @param dProject 项目实体类
     * @return : ice.server.comm.BaseOperateResult
     * @author : 沈明可
     * @date : 2019/9/15 20:57
     * User :
     */
    public BaseOperateResult update(DProject dProject){
        DProject dProject1 = this.get(dProject.getId());
        try {
            BeanUtil.copyNotNullProprties(dProject,dProject1);
            return BaseOperateResult.update(this.save(dProject1));
        } catch (Exception e) {
            e.printStackTrace();
            return BaseOperateResult.update(0);
        }
    }

    /**
     * 功能描述:〈项目删除〉
     * @param ids 项目id
     * @return : ice.server.comm.BaseOperateResult
     * @author : 沈明可
     * @date : 2019/9/15 20:57
     * User :
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String ids){
        //删除项目 下属app一并删除
        List<DProject> DProjectS = this.find(ParamBulider.build().addIn("id", ids).get());
        List<String> collect = DProjectS.stream().map(dProject -> dProject.getProjectCode()).collect(Collectors.toList());
        this.delete(ParamBulider.build().addIn("id", ids).get());
        dAppService.delete(ParamBulider.build().addIn("projectCode", StringUtils.join(collect,",")).get());
    }

}
